package com.qianfeng.xinyihezi.xinyihezi.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.query.Delete;
import com.bumptech.glide.Glide;
import com.qianfeng.xinyihezi.xinyihezi.R;
import com.qianfeng.xinyihezi.xinyihezi.activity.RankingActivity;
import com.qianfeng.xinyihezi.xinyihezi.activity.ShowActivity;
import com.qianfeng.xinyihezi.xinyihezi.activity.ZhuTiGuanActivity;
import com.qianfeng.xinyihezi.xinyihezi.adapter.MyGridAdapter;
import com.qianfeng.xinyihezi.xinyihezi.config.MyNetConfig;
import com.qianfeng.xinyihezi.xinyihezi.config.MyRetrofit;
import com.qianfeng.xinyihezi.xinyihezi.model.ADBean;
import com.qianfeng.xinyihezi.xinyihezi.model.PopcatBean;
import com.qianfeng.xinyihezi.xinyihezi.model.RankingBean;
import com.qianfeng.xinyihezi.xinyihezi.utils.GlideImageLoader;
import com.qianfeng.xinyihezi.xinyihezi.utils.MyGridView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 作者：王加威 on 2016/11/13 10:34
 */

public class FirstFragment extends Fragment/* implements SwipeRefreshLayout.OnRefreshListener */{

    private Banner mBanner;
    private ImageView mSLBX, mFKJZ, m0YCJ, mDHLW, mYYZ, mLK, mMGXSZ, mMSXC, mYYDB;
    private List<ADBean> mData, mData2;
    private List<RankingBean> mRankingBeens;
    private List<PopcatBean> mPopcatBeen;
    private ImageView[] mIvs2;
    private MyGridAdapter mGridAdapter;
    private MyGridView mGridView1,mGridView2;
    private TextView mMore;
    private boolean flag;
    private ImageView[] mIvs3;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.first_frgment, null);
        FragmentManager manager=getChildFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        ItemsFragment itemsFragment = new ItemsFragment();
        transaction.add(R.id.main_ViewPager,itemsFragment);
        transaction.commit();
        initView(view);
        loadData();
        setListener();
        return view;
    }


    private void setListener() {

        for (int i = 0; i < mIvs3.length; i++) {
            final int index=i;
            mIvs3[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(getActivity(), RankingActivity.class);
                    intent.putExtra("rc_id",mRankingBeens.get(index).rc_id);
                    getActivity().startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.in_from_right,R.anim.out_to_left);
                }
            });
        }
        mMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!flag) {
                    mGridView1.setVisibility(View.VISIBLE);
                    mGridView2.setVisibility(View.GONE);
                    mGridAdapter=new MyGridAdapter(getActivity(),mPopcatBeen);
                    mGridView1.setAdapter(mGridAdapter);
                    flag=true;
                }else {
                    mGridView2.setVisibility(View.VISIBLE);
                    mGridView1.setVisibility(View.GONE);
                    flag=false;
                }
            }
        });
        mGridView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getActivity(), ""+"还没做2", Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(getActivity(),ZhuTiGuanActivity.class);
                intent.putExtra("go_id",mPopcatBeen.get(position).go_id);
                intent.putExtra("obj_name",mPopcatBeen.get(position).obj_name);
                startActivity(intent);
            }
        });
        mGridView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getActivity(), ""+"还没做2", Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(getActivity(),ZhuTiGuanActivity.class);
                intent.putExtra("go_id",mPopcatBeen.get(position).go_id);
                intent.putExtra("obj_name",mPopcatBeen.get(position).obj_name);
                startActivity(intent);
            }
        });
    }


    private void initView(View view) {
        mMore = (TextView) view.findViewById(R.id.first_fragment_jiazaigengduo);
        mGridView1= (MyGridView) view.findViewById(R.id.fist_gridview1);
        mGridView2= (MyGridView) view.findViewById(R.id.fist_gridview2);
        mBanner = (Banner) view.findViewById(R.id.first_fragment_TopViewPager);
        mSLBX = (ImageView) view.findViewById(R.id.iv_fragment_SLBX);
        mFKJZ = (ImageView) view.findViewById(R.id.iv_fragment_FKJZ);
        m0YCJ = (ImageView) view.findViewById(R.id.iv_fragment_0YCJ);
        mDHLW = (ImageView) view.findViewById(R.id.iv_fragment_DHLW);
        mYYZ = (ImageView) view.findViewById(R.id.iv_fragment_YYZ);
        mLK = (ImageView) view.findViewById(R.id.iv_fragment_LK);
        mMGXSZ = (ImageView) view.findViewById(R.id.iv_fragment_MGXSZ);
        mMSXC = (ImageView) view.findViewById(R.id.iv_fragment_MSXC);
        mYYDB = (ImageView) view.findViewById(R.id.YYDB);
        mIvs2 = new ImageView[]{mSLBX, mSLBX, mFKJZ, m0YCJ, mDHLW, mYYZ, mLK, mMGXSZ, mMSXC, mYYDB};
        mIvs3 = new ImageView[]{mYYZ, mLK, mMGXSZ, mMSXC, mYYDB};

    }


    private void loadData() {
        mData = new ArrayList<>();
        mData2 = new ArrayList<>();
        mRankingBeens = new ArrayList<>();
        mPopcatBeen=new ArrayList<>();
        Retrofit mRetrofit = new Retrofit.Builder().baseUrl(MyNetConfig.BASE_PATH).build();
        MyRetrofit mInterface = mRetrofit.create(MyRetrofit.class);
//        List<MyJson> list = new Select().from(MyJson.class).where("jsoName=?", "First").execute();
//        if (list != null && list.size() > 0) {
//            long duration = System.currentTimeMillis() - list.get(0).time;
//            if (duration > 1000 * 60 * 2 ) {
//                Delete delete = new Delete();
//                delete.from(MyJson.class).where("jsoName=?", "First");
//            } else {
//                String s = list.get(0).json;
//                if (!TextUtils.isEmpty(s)) {
//
//                    parseJson(s);
//                }
//                return;
//            }
//        }
        mInterface.getData().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    Delete delete = new Delete();
//                    delete.from(MyJson.class).where("jsoName = ？", "First").execute();
                    try {
//                        MyJson json = new MyJson();
//                        json.jsoName = "First";
//                        json.json = response.body().string();
//                        json.time = System.currentTimeMillis();
//                        json.save();
                        parseJson(response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

    }

    private void parseJson(String s) {
        try {
            JSONObject json = new JSONObject(s);
            JSONObject data = json.getJSONObject("data");
            JSONArray banner = data.getJSONArray("banner");
            for (int i = 0; i < banner.length(); i++) {
                ADBean bean = new ADBean();
                JSONObject object = banner.getJSONObject(i);
                bean.image_url = object.optString("image_url");
                bean.images_share_url = object.optString("images_share_url");
                bean.name = object.optString("name");
                bean.table_name = object.optString("table_name");
                bean.url_descrip = object.optString("url_descrip");
                bean.url_name = object.optString("url_name");
                bean.save();
                mData.add(bean);
                Log.d("TAG", mData.size() + "<---------");
            }
            setPic();
            JSONArray bonus_banner = data.getJSONArray("bonus_banner");
            for (int i = 0; i < bonus_banner.length(); i++) {
                ADBean bean = new ADBean();
                JSONObject jsonObject = bonus_banner.getJSONObject(i);
                bean.image_url = jsonObject.getString("image_url");
                mData2.add(bean);
            }
           Glide.with(getActivity()).load(mData2.get(0).image_url).into(mSLBX);
           Glide.with(getActivity()).load(mData2.get(1).image_url).into(mFKJZ);
           Glide.with(getActivity()).load(mData2.get(2).image_url).into(m0YCJ);
           Glide.with(getActivity()).load(mData2.get(3).image_url).into(mDHLW);
            JSONArray ranking = data.getJSONArray("ranking");
            for (int i = 0; i < ranking.length(); i++) {
                RankingBean bean = new RankingBean();
                JSONObject object = ranking.getJSONObject(i);
                bean.freight = object.optString("freight");
                bean.goods_id = object.optString("goods_id");
                bean.html_src = object.optString("html_src");
                bean.image_url = object.optString("image_url");
                bean.like_count = object.optString("like_count");
                bean.p_price = object.optString("p_price");
                bean.price = object.optString("price");
                bean.product_id = object.optString("product_id");
                bean.rc_id = object.optString("rc_id");
                bean.sale_count = object.optString("sale_count");
                bean.share_url = object.optString("share_url");
                bean.short_description = object.optString("short_description");
                bean.short_name = object.optString("short_name");
                bean.store = object.optString("store");
                bean.type_id = object.optString("type_id");
                mRankingBeens.add(bean);
            }
            Glide.with(getActivity()).load(mRankingBeens.get(0).image_url).into(mYYZ);
            Glide.with(getActivity()).load(mRankingBeens.get(1).image_url).into(mLK);
            Glide.with(getActivity()).load(mRankingBeens.get(2).image_url).into(mMGXSZ);
            Glide.with(getActivity()).load(mRankingBeens.get(3).image_url).into(mMSXC);
            Glide.with(getActivity()).load(mRankingBeens.get(4).image_url).into(mYYDB);
            JSONArray pop_cat = data.getJSONArray("pop_cat");
            for (int i = 0; i < pop_cat.length(); i++) {
                PopcatBean bean=new PopcatBean();
                JSONObject object = pop_cat.getJSONObject(i);
                bean.description=object.getString("description");
                bean.disable=object.getString("disable");
                bean.go_id=object.getString("go_id");
                bean.image_url=object.getString("image_url");
                bean.obj_name=object.getString("obj_name");
                bean.p_order=object.getString("p_order");
                bean.type=object.getString("type");
                mPopcatBeen.add(bean);
            }
            mGridAdapter=new MyGridAdapter(getActivity(), mPopcatBeen.subList(0,6));
            mGridView2.setAdapter(mGridAdapter);

            mGridAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setPic() {
        List<String> urls=new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            urls.add(mData.get(i).image_url);
        }
        mBanner.setImageLoader(new GlideImageLoader());
        mBanner.setImages(urls);
        mBanner.isAutoPlay(true);
        mBanner.setDelayTime(1500);
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        mBanner.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent=new Intent(getActivity(), ShowActivity.class);
                intent.putExtra("url",mData.get(position).name);
                getActivity().startActivity(intent);
            }
        });
        mBanner.start();
    }


}
